package com.xiaoyi.util;

/**
 * @author xiaoyi
 * @version 1.0.0
 * @date 2023/07/31 09:51:00
 */

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import java.nio.charset.Charset;
import java.security.Security;
import java.util.Objects;


public class SM3Util {
    private SM3Util() {
    }

    static {
        // 防止内存中出现多次BouncyCastleProvider的实例
        if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    /**
     * 使用SM3算法计算给定输入的摘要值
     *
     * @param value 要进行摘要计算的输入字符串
     * @return 给定输入的摘要值
     */
    public static String encrypt(String value) {
        if (Objects.isNull(value) || "".equals(value)) {
            return "";
        }
        //创建 SM3Digest 对象
        SM3Digest digest = new SM3Digest();
        //将输入字符串转为字节数组，并使用该字节数组更新摘要对象的内部状态，以便进行计算
        byte[] inputBytes = value.getBytes(Charset.defaultCharset());
        digest.update(inputBytes, 0, inputBytes.length);
        //创建一个输出字节数组，调用 doFinal 方法完成哈希计算，并将结果存入输出数组
        byte[] output = new byte[digest.getDigestSize()];
        digest.doFinal(output, 0);
        //返回摘要字节数组
        return Hex.toHexString(output);
    }

    public static void main(String[] args) {
        String filePath = "这是中文和english的结合";
//        try {

//            byte [] inputBytes = Files.readAllBytes(Paths.get(filePath));
        String hexDigest = encrypt(filePath);
//            String hexDigest = Hex.toHexString(digest);
        System.out.println("SM3 Digest: " + hexDigest);
//        } catch (IOException e) {
//            System.out.println("An error occurred while reading the file: " + e.getMessage());
//        }
    }

}

